// 进程监控前端逻辑 - 主控制器
class ProcessMonitor {
    constructor() {
        this.sseSource = null;
        this.connections = [];
        this.processes = [];
        this.searchQuery = '';
        
        this.init();
    }

    init() {
        // 初始化事件处理器
        this.eventHandler = new ProcessEventHandler(this);
        this.eventHandler.setupEventListeners();
        this.eventHandler.setupTabs();
        this.eventHandler.setupKeyboardShortcuts();
        
        // 启动SSE连接获取实时数据
        this.startSSE();
        // 初始加载数据
        this.loadData();
    }

    startSSE() {
        // 使用SSE API客户端
        window.sseAPI.startProcessSSE();
        
        // 注册回调函数
        window.sseAPI.on('process', (data) => {
            this.updateRealTimeData(data);
        });
        
        window.sseAPI.on('error', (error) => {
            console.error('进程SSE错误:', error);
        });
    }

    stopSSE() {
        window.sseAPI.stopProcessSSE();
    }

    async loadData() {
        await Promise.all([
            this.loadConnections(),
            this.loadProcesses()
        ]);
    }

    async loadConnections() {
        try {
            console.log('开始加载连接数据...');
            const connections = await window.processAPI.getProcessConnections();
            console.log('连接数据加载成功:', connections);
            this.connections = connections || [];
            
            // 如果当前显示的是连接标签页，则进行过滤和渲染
            const activeTab = document.querySelector('.tab-button.active');
            if (activeTab && activeTab.getAttribute('data-tab') === 'connections') {
                this.filterConnections();
            }
        } catch (error) {
            console.error('加载连接数据失败:', error);
        }
    }

    async loadProcesses() {
        try {
            console.log('开始加载进程数据...');
            const result = await window.processAPI.getAllProcessStats();
            console.log('进程数据加载成功:', result);
            this.processes = result.processes || [];
            
            // 如果当前显示的是进程标签页，则进行渲染
            const activeTab = document.querySelector('.tab-button.active');
            if (activeTab && activeTab.getAttribute('data-tab') === 'processes') {
                this.renderProcesses();
            }
        } catch (error) {
            console.error('加载进程数据失败:', error);
        }
    }

    // 过滤和渲染数据
    filterAndRenderData() {
        const activeTab = document.querySelector('.tab-button.active');
        if (activeTab) {
            const tabName = activeTab.getAttribute('data-tab');
            
            // 设置排序器的当前标签页类型
            if (window.processSorter) {
                window.processSorter.setTabType(tabName);
            }
            
            if (tabName === 'connections') {
                this.filterConnections();
            } else if (tabName === 'processes') {
                this.renderProcesses();
            }
        }
    }

    filterConnections() {
        const showListeningElem = document.getElementById('show-listening');
        const showEstablishedElem = document.getElementById('show-established');
        const processFilterElem = document.getElementById('process-filter');
        const portFilterElem = document.getElementById('port-filter');
        
        const showListening = showListeningElem ? showListeningElem.checked : false;
        const showEstablished = showEstablishedElem ? showEstablishedElem.checked : true;
        const processFilter = processFilterElem ? processFilterElem.value.toLowerCase() : '';
        const portFilter = portFilterElem ? portFilterElem.value : '';

        let filtered = this.connections.filter(conn => {
            // 状态过滤
            if (!showListening && conn.status === 'LISTEN') return false;
            if (!showEstablished && conn.status === 'ESTABLISHED') return false;

            // 进程名过滤
            if (processFilter && !conn.process_name.toLowerCase().includes(processFilter)) return false;

            // 端口过滤
            if (portFilter) {
                const port = parseInt(portFilter);
                if (conn.local_port !== port && conn.remote_port !== port) return false;
            }

            return true;
        });

        // 使用排序器排序
        const sortedConnections = window.processSorter.sortConnections(filtered);
        
        // 设置分页数据
        window.connectionsPagination.setFilteredData(sortedConnections);
        
        // 渲染第一页数据
        const pageData = window.connectionsPagination.getCurrentPageData();
        this.renderConnections(pageData);
    }

    renderConnections(connections) {
        window.processRenderer.renderConnections(connections);
        window.processRenderer.updateSummaryCards();
    }

    renderProcesses() {
        // 使用排序器排序
        const sortedProcesses = window.processSorter.sortProcesses(this.processes);
        
        // 设置分页数据
        window.processesPagination.setFilteredData(sortedProcesses);
        
        // 渲染第一页数据
        const pageData = window.processesPagination.getCurrentPageData();
        window.processRenderer.renderProcesses(pageData);
        
        // 更新统计卡片（基于所有数据，不分页）
        window.processRenderer.updateSummaryCardsFromProcesses(this.processes);
    }

    updateRealTimeData(data) {
        if (data.processes) {
            this.processes = data.processes;
        }
        
        // 更新汇总统计
        if (data.summary) {
            window.processRenderer.updateSummaryCards(data.summary);
        }

        // 更新显示时间
        document.getElementById('update-time').textContent = data.timestamp || new Date().toLocaleTimeString();
        
        // 重新渲染当前标签页数据
        this.filterAndRenderData();
    }

    async showProcessDetail(pid) {
        try {
            const result = await window.processAPI.getProcessStats(pid);
            window.processRenderer.renderProcessDetail(result);
        } catch (error) {
            console.error('加载进程详情失败:', error);
        }
    }

    closeModal() {
        document.getElementById('process-detail-modal').style.display = 'none';
    }
}

// 初始化进程监控
// 使用更安全的初始化方式
function initProcessMonitor() {
    console.log('初始化 ProcessMonitor...');
    try {
        const processMonitor = new ProcessMonitor();
        // 将实例绑定到 window 供其他地方使用
        window.processMonitor = processMonitor;
        console.log('ProcessMonitor 初始化成功');
    } catch (error) {
        console.error('ProcessMonitor 初始化失败:', error);
    }
}

// 等待DOM完全加载
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initProcessMonitor);
} else if (document.readyState === 'interactive' || document.readyState === 'complete') {
    // 如果 DOM 已经加载完成，等待一个微任务周期再初始化
    setTimeout(initProcessMonitor, 0);
}